<template>  
  <div  
    class="uploadContainer"  
    @dragenter="handleDragEnter"  
    @dragover.prevent="handleDragOver"  
    @dragleave.prevent="handleDragLeave"  
    @drop="handleDrop"  
  >  
    <slot></slot>  
    <div class="overlay" :class="{shadow: isDraggingOver && imgList.length < 1}" v-if="isDraggingOver || imgList.length > 0">
      <div class="uploadContent" v-if="imgList.length > 0">
        <div class="headerInfo">
          <span>发送给</span>
          <div class="userInfo">
            <img src="@/assets/images/tx.jpg"/>
            <span>baby</span>
          </div>
        </div>
        <div class="imgListWrapper scroller">
          <div class="imgWrapper" v-for="(img, index) in imgList" :key="img.name" @mouseenter="img.showDelete = true" @mouseleave="img.showDelete = false">
            <img :src="img.base64"/>
            <div class="infoWrapper">
              <div class="imgInfo">
                <div class="nameWrapper">
                  <div class="name">{{img.name.split('.')[0]}}</div>
                  <span class="type">.{{img.name.split('.')[1]}}</span>
                </div>
                <span class="size">{{formatSize(img.size)}}</span>
              </div>
              <div class="delete" @click="deleteIndex(index)" v-if="img.showDelete">删除</div>
            </div>
          </div>
        </div>
        <div class="btns">
          <input placeholder="给朋友留言"/>
          <div>
            <button @click='uploadImgList'>发送</button>
            <button class="canncel" @click="cancelUpload">取消</button>
          </div>
        </div>
      </div>
    </div>  
  </div>  
</template>  
  
<script lang="ts" setup>  
import { ref, defineEmits } from 'vue';  
import { uploadFile } from '@/lib/api'  
const isDraggingOver = ref<boolean>(false);  
const imgList = ref([])
let dragLeaveTimeout: number | undefined;  
const emit = defineEmits(['uploadImg'])

// 格式化文件大小
const formatSize = (size: number) => {
  return size > 1024 * 1024 ? `${(size / 1024 / 1024).toFixed(2)}MB` : `${(size / 1024).toFixed(2)}KB`
}

// 删除图片
const deleteIndex = (index: number) => {
  imgList.value.splice(index, 1)
}

// 取消上传
const cancelUpload = () => {
  imgList.value = []
  isDraggingOver.value = false
}

// 上传数据
const uploadImgList = () => {
  emit('uploadImg', imgList.value)
  imgList.value = []
  isDraggingOver.value = false
}
  
// 拖曳事件处理
const handleDragEnter = () => {  
  isDraggingOver.value = true;  
};  
  
const handleDragOver = (e: Event) => {  
  e.preventDefault();  
  // 保持拖拽状态为true  
  clearTimeout(dragLeaveTimeout as number); // 清除可能的离开定时器  
};  

const handleDragLeave = () => {  
  // 设置一个短暂的延迟，以便在用户短暂离开时不会立即隐藏遮罩层  
  dragLeaveTimeout = window.setTimeout(() => {  
      // 检查拖拽区域是否仍然处于hover状态（这通常意味着鼠标没有在上面）  
      // 注意：这种方法可能不是100%准确，因为它依赖于:hover伪类  
      // 在更复杂的布局中，可能需要更精确的方法来确定鼠标位置  
      isDraggingOver.value = false;  
  }, 100); // 延迟时间可以根据需要调整  
};  

const handleDrop = (e: DragEvent) => {
  e.preventDefault();
  clearTimeout(dragLeaveTimeout as number); // 清除离开定时器
  isDraggingOver.value = false; // 通常在drop后隐藏遮罩层，但也可以根据需要保持显示
  const files = e.dataTransfer.files;

  console.log('@files', files); // 检查 files 是否为空

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    //uploadFile(file)
    console.log('file 是否为 File 对象:', file instanceof File); // 检查 file 是否为 File 对象

    const reader = new FileReader();
    reader.onload = (event) => {
      const formData = new FormData();
      formData.append('file', file);
      const base64 = event.target.result as string;
      imgList.value.push({
        file: formData,
        name: file.name,
        type: file.type,
        size: file.size,
        base64: base64, // 去掉前缀 "data:image/png;base64,"
        showDelete: false
      });
    };

    reader.readAsDataURL(file);
  }
};
</script>  
  
<style lang="less" scoped>  
@import'@/assets/base.less';
.uploadContainer {  
  position: relative;  
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .overlay {  
    width: 100%;
    height: 100%;
    position: absolute;  
    top: 0;  
    left: 0;  
    right: 0;  
    bottom: 0;  
    display: flex;
    align-items: center;
    justify-content: center; 
    &.shadow {
      background-color: rgba(0, 0, 0, 13%); /* 初始透明 */  
    }
    .uploadContent {
      width: 30%;
      background-color: white;
      border-radius: 5px;
      padding: 15px;
      box-shadow: 2px 2px 10px #ccc;
      .headerInfo {
        padding-bottom: 10px;
        border-bottom: 1px solid #f1f1f1;
        margin-bottom: 10px;
        span {
          font-size: 15px;
        }
        .userInfo {
          margin-top: 10px;
          display: flex;
          align-items: center;
          gap: 10px;
          img {
            height: 38px;
            height: 38px;
            border-radius: 2px;
          }
        }
      }
      .imgListWrapper {
        height: 250px;
        display: flex;
        flex-direction: column;
        gap: 10px;
        overflow-y: scroll;
        .imgWrapper {
          display: flex;
          flex-direction: row;
          /* align-items: baseline; */
          gap: 10px;
          >img {
            height: 38px;
            width: 38px;
            border-radius: 2px;
          }
          .infoWrapper {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 20px;
            overflow: hidden;
            .imgInfo {
              display: flex;
              flex-direction: column;
              font-size: 15px;

              width: 75%;
              .nameWrapper {
                display: flex;
                .name {
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                }
                .delete {
                  width: 80px;
                  cursor: pointer;
                }
              }
  
              .size {
                font-size: 13px;
                color: #a5a5a5;
              }
            }
            .delete {
              flex: 1;
              text-align: center;
              color: #6d93c1;
              font-size: 13px;
              &:hover {
                color: #1e62b4;
              }
            }
          }
        }
      }
      .btns {
        margin-top: 20px;
        border-radius: 3px;
        input {
          background-color: #f3f3f3;
          border: none;
          width: 100%;
          height: 30px;
          border-radius: 3px;
          padding: 10px;
          box-sizing: border-box;
          outline: none;
        }
        div {
          display: flex;
          gap: 20px;
          margin-top: 10px;
          button {
            width: 50%;
            height: 34px;
            border: none;
            color: white;
            background-color: #30b96a;
            border-radius: 3px;
            outline: none;
            &.canncel {
              background-color: #ecececcc;
              color: #30b96a;
            }
          }
        }
      }
    }
  }  

}  
  

</style>